﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using Robert.TwitBy.ViewModels;
using Robert.TwitBy.Models;
using System.Windows.Media.Animation;
using Robert.TwitBy.Properties;

namespace Robert.TwitBy.Views
{
	public partial class MainPage
	{
		public MainPage(TwitterViewModel model)
		{
			this.InitializeComponent();

            _model = model;
            _model.Dispatcher = this.Dispatcher;

            this.DataContext = _model;
            this.tweetsListBox.SelectionChanged += tweetsListBox_SelectionChanged;
            this.tweetsListBox.SelectionMode = SelectionMode.Single;
            this.tweetsListBox.MouseDoubleClick += new MouseButtonEventHandler(tweetsListBox_MouseDoubleClick);
            this.tweetTextBox.TextChanged += new TextChangedEventHandler(tweetTextBox_TextChanged);

            _loadToolbar = this.Resources["LoadToolbarStoryboard"] as Storyboard;
            _unloadToolbar = this.Resources["UnloadToolbarStoryboard"] as Storyboard;

            _model.UpdateFollowersCommand.Execute(null);
		}

        void tweetTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (tweetTextBox.IsFocused)
                return;
            else
            {
                tweetTextBox.Focus();
                tweetTextBox.SelectionStart = tweetTextBox.Text.Length;
            }
        }

        void tweetsListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.tweetsListBox.SelectedIndex = -1;
        }

        void tweetsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_model.SelectedItem == null && this.Toolbar.Height != 0)
            {
                _unloadToolbar.Begin();
                _model.IsSelected = true;
            }
            else
                if (this.Toolbar.Height == 0 && _model.SelectedItem != null)
                {
                    _loadToolbar.Begin();
                    _model.IsSelected = false;
                }
        }

        private TwitterViewModel _model;
        private Storyboard _loadToolbar;
        private Storyboard _unloadToolbar;
	}
}